import styled from "@emotion/styled";
import { LegacyRef, createRef, memo, useState } from "react";
import { CloseOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router";
import { useRecoilState } from "recoil";
import { getNaviParentIds, naviState } from "../../stores/navi";
import { userState } from "../../stores/user";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
/**
 * 自定义顶部tab
 */
const CustomTabBar = () => {
  const navigate = useNavigate();
  const [navi, setNavi] = useRecoilState(naviState);
  const [user] = useRecoilState(userState);
  const [transform,] = useState<number>(0);

  const refContainer = createRef<LegacyRef<HTMLDivElement>>();
  const refList = createRef<LegacyRef<HTMLDivElement>>();


  /**
   * 删除一个tab
   * @param index tab 下标
   */
  const removeTab = (index: number) => {
    const newNavi = navi.tabHistory.filter((history, i) => {
      return index !== i;
    });
    let activeIndex = 0;
    if (navi.tabActiveIndex === index) {
      //删除的是选中的Tab
      if (index === navi.tabHistory.length - 1) {
        //如果是最后一项,选中往前移动一位
        activeIndex = index - 1;
      } else {
        //不是最后一项,选中往后移动一位
        activeIndex = index;
      }
      activeIndex === 0 ? navi.tabActiveIndex : activeIndex;
      //获取到所有的menu父节点并展开
      const parentIds = getNaviParentIds(
        parseInt(newNavi[activeIndex].key[0]),
        user.route || [],
        []
      );
      const naviData = {
        ...navi,
        tabHistory: newNavi,
        defaultOpenKeys: parentIds,
        defaultSelectedKeys: newNavi[activeIndex].key,
        tabActiveIndex: activeIndex,
      };
      setNavi(naviData);
      sessionStorage.setItem("__BEEFSOLVE_BACKWEB__NAVI__", JSON.stringify(naviData));
    } else {
      setNavi({
        ...navi,
        tabHistory: newNavi,
      });
      sessionStorage.setItem(
        "__BEEFSOLVE_BACKWEB__NAVI__",
        JSON.stringify({
          ...navi,
          tabHistory: newNavi,
        })
      );
    }
  };
  return (
    <CustomTabBarContainer>
      <span className="left-icon">
        <LeftOutlined />
      </span>
      <div className="custom-tab-bar-list-container" ref={refContainer.current}>
        <div
          ref={refList.current}
          className="custom-tab-bar-list"
          style={{ transform: `translateX(${transform})` }}
        >
          {navi.tabHistory.map((tab, index) => {
            return (
              <div key={index}>
                <span
                  className={navi.tabActiveIndex === index ? "active" : ""}
                  onClick={() => {
                    //获取到所有的menu父节点并展开
                    const parentIds = getNaviParentIds(
                      parseInt(tab.key[0]),
                      user.route || [],
                      []
                    );
                    const naviData = {
                      ...navi,
                      defaultSelectedKeys: [tab.key + ""],
                      defaultOpenKeys: parentIds,
                      tabActiveIndex: index,
                    };
                    setNavi(naviData);
                    sessionStorage.setItem(
                      "__BEEFSOLVE_BACKWEB__NAVI__",
                      JSON.stringify(naviData)
                    );
                    navigate({ pathname: tab.path });
                  }}
                >
                  {tab.title}
                </span>
                {index !== 0 ? (
                  <CloseOutlined
                    className="tab-close-icon"
                    onClick={() => {
                      removeTab(index);
                    }}
                  />
                ) : null}
              </div>
            );
          })}
        </div>
      </div>
      <span className="right-icon">
        <RightOutlined />
      </span>
    </CustomTabBarContainer>
  );
};

export default memo(CustomTabBar);

const CustomTabBarContainer = styled.div`
  overflow: hidden;
  height: 100%;
  display: flex;
  padding: 0 24px;
  position: relative;
  .custom-tab-bar-list-container {
    width: 100%;
    overflow: hidden;
    // border: 1px solid green;
  }
  .custom-tab-bar-list {
    display: inline-block;
    // border: 1px solid red;
    transition: transform 0.5s ease-in-out;
    > div {
      font-size: 14px;
      float: left;
      height: 32px;
      line-height: 32px;
      background: var(${`--sencond-bg-color`});
      border-radius: 3px;
      border: none;
      margin-right: 6px;
      color: var(${`--gary-400-color`});
      cursor: pointer;
      padding: 3px 16px 3px;
      margin-top: 5px;
      transition: all 0.3s ease-in-out;
      &:hover {
        color: var(${`--primary-block-color`});
      }
    }
    .tab-close-icon {
      margin-left: 12px;
      font-size: 12px;
    }
    .active {
      color: var(${`--primary-color`});
    }
  }
  .left-icon {
    position: absolute;
    left: 0;
    height: 100%;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .right-icon {
    position: absolute;
    right: 0;
    height: 100%;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
  }
`;
